package client.meetingview;

import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.BoxLayout;
import javax.swing.JTable;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;

import miscellaneous.Storage;
import miscellaneous.TimeSupport;

import client.popups.wizard.AppointmentWizard;
import data.Appointment;
import data.Meeting;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.Calendar;
import java.util.List;

/**
 * Shows the appointments in a table
 * @author daniel
 */

public class AppointmentPane extends JPanel implements PropertyChangeListener {
	
	private JTable table;
	private JButton btnInnkalleTilNytt;
	private String[] columnames = {"Type","Møteleder","Dag", "Starttidspunkt","Tittel","Beskrivelse","Varighet"};
	private List<Appointment> list;

	private DefaultTableModel tableModel;
	private JScrollPane scrollPane;

	/**
	 * The constructor
	 * @param list The AppoitmentList that always will show
	 */
	public AppointmentPane() {
		list = Storage.getUpComingAppointmentsAndMeetings();
		
		Storage.addListener(this);

		setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));

		btnInnkalleTilNytt = new JButton("Innkalle til nytt møte");
		add(btnInnkalleTilNytt);
		btnInnkalleTilNytt.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				createAppointment();
			}
		});

		scrollPane = new JScrollPane();
		add(scrollPane);

		tableModel = new DefaultTableModel() {
			@Override
			public boolean isCellEditable(int rowIndex, int mColIndex) {
				return false;
			}
		};

		tableModel.setColumnIdentifiers(columnames);
		table = new JTable(tableModel);
		scrollPane.setViewportView(table);

		table.setDefaultRenderer(Object.class, new TableRenderer());
		table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);

		ListSelectionModel selectionModel = table.getSelectionModel();
		selectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

		selectionModel.addListSelectionListener(new ListSelectionListener() {
			@Override
			public void valueChanged(ListSelectionEvent event) {
				if(!event.getValueIsAdjusting()) {
					table.setFocusable(false);
					if(table.getSelectedRow() >= 0)
						changeAppointment(table.getSelectedRow());
					table.getSelectionModel().clearSelection();
				}

			}
		});
		updateTable();
	}

	/**
	 * Updates the table with information from the AppointmentList
	 */
	private void updateTable() {
		if(tableModel == null)
			return;
		
		this.list = Storage.getUpComingAppointmentsAndMeetings();
		String [][] information = new String[list.size()][columnames.length]; 
		for (int i = 0; i < information.length; i++) {
			//It is possible another better way to do this rather than
			//dividing up the object and mark a String to separate them
			if(list.get(i) instanceof Meeting ) {
				information[i][0] = "Møte";
			} else if (list.get(i) instanceof Appointment) {
				information[i][0] = "Avtale";
			} else {
				//should never happen
				information[i][0] = "Udefinert";
			}
			
			if(list.get(i).getOwner() != null) {
				information[i][1] = list.get(i).getOwner().getName();
			} else {
				information[i][1] = "Ingen leder";
			}

			int nrInNorweginDayList = list.get(i).getReservation().
				getStartTime().get(Calendar.DAY_OF_WEEK)-2;
			
			if(nrInNorweginDayList < 0) {
				nrInNorweginDayList = TimeSupport.daysByNumber.length + nrInNorweginDayList;
			}
			        			        
			information[i][2] = TimeSupport.daysByNumber[nrInNorweginDayList];
			information[i][3] = TimeSupport.showTimeNice(list.get(i).
			        getReservation().getStartTime()) + " " +
			        TimeSupport.showDateNice(list.get(i).getReservation().getStartTime());
			information[i][4] = list.get(i).getTitle();
			information[i][5] = list.get(i).getDescription();
			//if duration is 0, this is a remainder
			if(list.get(i).getReservation().getDuration() == 0 ) {
				information[i][4] = "Huskelapp";
			} else {
				int hour = list.get(i).getReservation().getDuration() / 60;
				int minute = (list.get(i).getReservation().getDuration() % 60 );
				information[i][6] = hour + " time(r) og " + minute  + " minutter";
			}
		}
		tableModel.setDataVector(information, columnames);
	}

	/**
	 * Creates a new frame for creating a new appointment
	 */
	public void createAppointment() {
		new AppointmentWizard().setVisible(true);
	}

	/**
	 * Creates a new frame that allows to change the selected (by index)
	 * appointment
	 * @param index The index of the meeting (from AppointmentList) that
	 * we will change
	 */
	public void changeAppointment(int index) {
		Appointment a = list.get(index);
		if(a != null) {
			a.requestEdit();
		}
	}

	@Override
	public void propertyChange(PropertyChangeEvent evt) {
		updateTable();
	}
}